<template>
  <div v-if="isLoading" class="loading-container">
    <el-skeleton :rows="3" animated />
  </div>
  <div v-else-if="currentPage" class="training-view">
    <training-wrapper
      :scene-name="sceneName"
      :current-index="currentIndex"
      :total-exercises="totalExercises"
      :can-navigate-previous="true"
      :can-navigate-next="true"
      @previous="handlePrevious"
      @next="handleNext"
    >
      <Suspense>
        <template #default>
          <component
            :is="getTrainingComponent"
            v-bind="currentPage"
            @complete="handlePageComplete"
          />
        </template>
        <template #fallback>
          <div class="loading-container">
            <el-skeleton :rows="3" animated />
          </div>
        </template>
      </Suspense>
    </training-wrapper>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, defineAsyncComponent } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useTrainingStore } from '@/stores/training'
import { TrainingType } from '@/types/training'
import { ElMessage } from 'element-plus'
import TrainingWrapper from '@/components/TrainingWrapper.vue'

const route = useRoute()
const router = useRouter()
const trainingStore = useTrainingStore()

const isLoading = computed(() => trainingStore.isLoading)
const currentPage = computed(() => trainingStore.getCurrentPage())

// 计算属性
const sceneName = computed(() => trainingStore.sceneName)
const currentIndex = computed(() => trainingStore.currentIndex)
const totalExercises = computed(() => trainingStore.totalPages)

// 根据训练类型获取对应的组件
const getTrainingComponent = computed(() => {
  console.log('getTrainingComponent called')
  if (!currentPage.value) return null

  switch (currentPage.value.type) {
    case TrainingType.IMAGE_CHOOSE_AUDIO:
      console.log('ImageChooseAudio')
      return defineAsyncComponent(() => import('@/views/listen/ImageChooseAudio.vue'))
    case TrainingType.AUDIO_BASE:
      console.log('AudioBase')
      return defineAsyncComponent(() => import('@/views/listen/AudioBase.vue'))
    case TrainingType.AUDIO_CHOOSE_IMAGE:
      console.log('AudioChooseImage')
      return defineAsyncComponent(() => import('@/views/listen/AudioChooseImage.vue'))
    default:
      return null
  }
})

// 处理页面完成
const handlePageComplete = async () => {
  if (!currentPage.value) return

  // 更新页面完成状态
  trainingStore.updatePageCompletion(currentPage.value.id, true)
  handleNext()
}

// 处理上一页
const handlePrevious = () => {
  trainingStore.moveToPreviousPage()
}

// 处理下一页
const handleNext = () => {
  const hasNextPage = trainingStore.moveToNextPage()
  if (!hasNextPage) {
    // 训练计划完成
    ElMessage.success('恭喜！你已完成所有训练')
    router.push('/')
  }
}

// 初始化训练计划
onMounted(async () => {
  const sceneId = route.params.sceneId as string
  console.log('Fetching training plan for scene:', sceneId)
  try {
    await trainingStore.fetchSceneTrainingPlan(sceneId)
    console.log('Current Plan:', trainingStore.currentPlan)
    console.log('Current Index:', trainingStore.currentIndex)
    console.log('Total Pages:', trainingStore.totalPages)
  } catch (error) {
    console.error('Error fetching training plan:', error)
    ElMessage.error('加载训练计划失败')
    router.push('/')
  }
})
</script>

<style scoped>
.loading-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.training-view {
  min-height: 100vh;
}
</style>
